package com.kyz.speechsdk.engine;

import android.util.Log;


import com.kyz.speechsdk.engine.abstracts.BaseUnderstandingEngine;
import com.kyz.speechsdk.engine.entity.EngineResult;
import com.kyz.speechsdk.engine.entity.ExcelData;
import com.kyz.speechsdk.engine.helper.LocalStoreHelper;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * create by ZhongZihao on 2020/12/29
 * 本地文件语义匹配
 */
public class LocalEngine extends BaseUnderstandingEngine {
    private static final String TAG = "TAG_LocalEngine";

    private String configFilePath;

    public String getConfigFilePath() {
        return configFilePath;
    }

    public void setConfigFilePath(String configFilePath) {
        this.configFilePath = configFilePath;
        boolean isLoad = LocalStoreHelper.loadExcelConfigure(this.configFilePath);
        Log.d("LocalConfigPath", "localFilePath: " + configFilePath);
        if (!isLoad) {
            Log.e("LocalConfigPath", "加载本地语义库配置失败...");
        }
    }

    private LocalEngine(Builder builder) {
        setConfigFilePath(builder.configFilePath);
        setNextEngine(builder.engine);
    }

    @Override
    protected void requestTextUnderstand(String text,boolean isChainUnderstand) {
        ExcelData excelData = LocalStoreHelper.matchAnswer(text);
        if (excelData != null) {
            String result = generateJsonAnswer(excelData);
            onEngineResult(new EngineResult(result, EngineResult.ENGINE_LOCAL));
        } else {
            if (isChainUnderstand) {
                nextEngineChainTextUnderstand(text);
            }
        }
    }

    private String generateJsonAnswer(ExcelData excelData) {
        String reply = "";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("answer", excelData.getRandomAnswer());
            jsonObject.put("catalogue", excelData.getCatalogue());
            jsonObject.put("catalogueID", excelData.getCatalogueID());
            reply = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return reply;
    }

    public static class Builder {
        private String configFilePath;
        private BaseUnderstandingEngine engine;

        public Builder setConfigFilePath(String configFilePath) {
            this.configFilePath = configFilePath;
            return this;
        }

        public Builder setNextEngine(BaseUnderstandingEngine engine) {
            this.engine = engine;
            return this;
        }

        public LocalEngine build() {
            return new LocalEngine(this);
        }
    }

    @Override
    public void destoryEngine() {
        super.destoryEngine();
        Log.i(TAG, "destoryEngine: LocalEngine.....");
    }
}
